package com.entrogy.service.impl;

import com.entrogy.bean.*;
import com.entrogy.dao.ClassMapper;
import com.entrogy.dao.PositionMapper;
import com.entrogy.dao.SchoolMapper;
import com.entrogy.service.ClassService;
import com.entrogy.utils.THDio;
import com.entrogy.utils.constants.Constants;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class ClassServiceImpl implements ClassService {

	private Logger logger = LoggerFactory.getLogger(ClassServiceImpl.class);

	@Autowired
	private ClassMapper mapper;

	@Autowired
	private SchoolMapper schoolMapper;

	@Autowired
	private PositionMapper positionMapper;

	@Autowired
	private THDio thd;

	@Override
	public int insertGrade(int id,String className,Integer parentId,int schoolCode) {
		if (String.valueOf(id).substring(4,5).equals("0")){
			// 如果在新增年级，那么就在static_cycle和static_arrange表中初始化这个年级的作息时间数据
			String schoolName = schoolMapper.getSchoolName(schoolCode);
			// 一个年级的学生的出门时间段有中午、下午、晚上三个，那么排列组合计算得出总共有八种出门类型，分别用000,001,011,111,010,100,110,101表示
			String[] outTypes = {"001","010","011","100","101","110","111","000"};
			// 初始化所有年级的通行时间段是一样的
			String[] timeSlots = {"22:30-23:00","17:30-18:30","17:30-18:30;22:30-23:00",
					"12:00-14:00","12:00-14:00;22:30-23:00","12:00-14:00;17:30-18:30",
					"12:00-14:00;17:30-18:30;22:30-23:00","00:00-00:00"};
			// 实义德后台的时段名称存储格式为：熵熵中学高2017级000
			for (int i = 0; i < outTypes.length; i++) {
				String outType = outTypes[i];
				String timeSlot = timeSlots[i];
				String cycleName = schoolName + className + outType;
				JSONObject reqSubmitCycle = new JSONObject();
				reqSubmitCycle.put("name", cycleName);
				reqSubmitCycle.put("type", 3);
				reqSubmitCycle.put("cycle_value", getCycleValue());
				logger.info("新建年级：设置时间段开始 " + reqSubmitCycle.toString());
				SchoolThdidUrlEntity schoolThdidUrl = schoolMapper.getSchoolThdidUrlAndGroupInfo(schoolCode, Constants.THDID_AI06);
				JSONObject resSubmitCycle = thd.THD_interface(schoolThdidUrl.getPathUrl(), "/competence/submit_cycle", reqSubmitCycle, false, schoolThdidUrl.getAccessToken());
				logger.info("新建年级：设置时间段结束 " + resSubmitCycle.toString());
				Integer cycleId = 0;
				if (resSubmitCycle.getInt("code") == 0){
					// 注意：实义德新版本后台接口有变化，cycle_id返回为null
//					cycleId = resSubmitCycle.getJSONObject("data").getInt("cycle_id");
				}
				Integer type = outType.equals("000") ? 0 : 1;
				int initStaticCycleRow = mapper.insertGradeStaticCycle(id, outType, null, cycleName, type, timeSlot, schoolCode);
			}
			// 然后往static_arrange中初始化数据，有四种类型，分别是正常日、离校日、返校日、放假日
			List<StaticArrangeEntity> staticArrangeList = new ArrayList<>();
			StaticArrangeEntity staticArrange = new StaticArrangeEntity(id, 1, "12:00-14:00", "17:30-18:30", "22:00-23:00", "7", schoolCode);
			staticArrangeList.add(staticArrange);
			staticArrange = new StaticArrangeEntity(id, 2, "12:00-14:00", "17:30-18:30", "22:00-23:00", "1234", schoolCode);
			staticArrangeList.add(staticArrange);
			staticArrange = new StaticArrangeEntity(id, 3, "11:55-12:55", "15:40-20:00", "00:00-00:00", "5", schoolCode);
			staticArrangeList.add(staticArrange);
			staticArrange = new StaticArrangeEntity(id, 4, "00:00-00:00", "00:00-00:00", "00:00-00:00", "6", schoolCode);
			staticArrangeList.add(staticArrange);
			int initStaticArrangeRow = mapper.insertStaticArrange(staticArrangeList);
		}
		return mapper.insertGrade(id,className,parentId,schoolCode);
	}

	@Override
	public int insertUserAndClass(int userId, int classId) {
		return mapper.insertUserAndClass(userId,classId);
	}

	@Override
	public List<ClassEntity> getClassList(Map<String,Object>  map) {
		return mapper.getClassList(map);//查询所有的班级列表
	}

	@Override
	public int deleteClass(int id, Integer schoolCode) {
		int deleteClassRow = mapper.deleteClass(id, schoolCode);
		// 删除实义德后台的时段规则
		List<Integer> cycleIdList = mapper.listGradeCycle(id, schoolCode);
		logger.debug(cycleIdList.toString());
		StringBuilder cycleIds = new StringBuilder();
		for (Integer s : cycleIdList) {
			cycleIds.append(";").append(s);
		}
		JSONObject reqSubmitCycle = new JSONObject();
		if (cycleIds != null && cycleIds.length() != 0){
			reqSubmitCycle.put("cycle_ids", cycleIds.substring(1));
			SchoolThdidUrlEntity schoolThdidUrl = schoolMapper.getSchoolThdidUrlAndGroupInfo(schoolCode, Constants.THDID_AI06);
			JSONObject resSubmitCycle = thd.THD_interface(schoolThdidUrl.getPathUrl(), "/competence/cycle_delete", reqSubmitCycle, false, schoolThdidUrl.getAccessToken());
			logger.info("删除年级时，删除实义德后台时间规则结果=》" + reqSubmitCycle.toString());
		}else {
			logger.info("该年级的时间规则表id没有，gradeId=>" + id);
		}
		// 该年级的早上考勤时间段信息也要删除
		int deleteGradeRow = mapper.deleteGradeMorningAttendanceTime(id, schoolCode);
		// 删除年级的时候还得删除时间安排表以及时间规则表
		int deleteGradeStaticArrange = mapper.deleteGradeStaticArrange(id, schoolCode);
		int deleteGradeStaticCycle = mapper.deleteGradeStaticCycle(id, schoolCode);
		return deleteClassRow;
	}

	@Override
	public int insertClassType(String typeName,int schoolCode) {
		return mapper.insertClassType(typeName,schoolCode);
	}

	@Override
	public List<ClassTypeEntity> getClassTypeList(int schoolCode) {
		return mapper.getClassTypeList(schoolCode);
	}

	@Override
	public int updateClassInformation(int classId, int classTypeId, String className, Integer schoolCode) {
		return mapper.updateClassInformation(classId, classTypeId, className, schoolCode);
	}

	@Override
	public int deleteClassType(int id) {
		return mapper.deleteClassType(id);
	}


	/**
	 *   根据id 查询class
	 * @param id
	 * @return
	 */
	@Override
	public ClassEntity getClassById(int id,int schoolCode){
		return mapper.getClassById(id,schoolCode);
	};


	/**
	 *   查询总数
	 * @param map
	 * @return
	 */
	public int getClassListTotal( Map<String,Object>  map){
		return mapper.getClassListTotal(map);
	}

	@Override
	public ClassEntity getClassByClassLeaderId(String uid) {
		return mapper.getClassByClassLeaderId(uid);
	}

	@Override
	public GradeEntity getGradeByGradeLeaderId(String uid) {
		return mapper.getGradeByGradeLeaderId(uid);
	}

	@Override
	public List<Integer> listGradeIdBySchoolCode(Integer schoolCode) {
		return mapper.listGradeIdBySchoolCode(schoolCode);
	}

	@Override
	public List<Integer> listClassLeaderManagementClassId(String teacherId) {
		return mapper.listClassLeaderManagementClassId(teacherId);
	}

	@Override
	public List<Integer> listGradeLeaderManagementClassId(String teacherId) {
		return mapper.listGradeLeaderManagementClassId(teacherId);
	}

	@Override
	public int getGradeIdByClassId(int classId, Integer schoolCode) {
		return mapper.getGradeIdByClassId(classId, schoolCode);
	}

	@Override
	public String getClassLeader(int schoolCode, String gradeId, String classId) {
		return positionMapper.getClassLeader(Integer.valueOf(classId), schoolCode).getTeacherId();
	}

	@Override
	public StaticCycleEntity getStaticCycle(int gradeId, Integer schoolCode, String allowTime) {
		return mapper.getStaticCycle(gradeId, schoolCode, allowTime);
	}

	@Override
	public String getGradeLeaderId(Integer schoolCode, Integer gradeId) {
		return mapper.getGradeLeaderId(schoolCode, gradeId);
	}

	@Override
	public List<Integer> listClassIdBySchoolCode(Integer schoolCode, Integer gradeId) {
		return mapper.listClassIdBySchoolCode(schoolCode, gradeId);
	}

	@Override
	public List<com.alibaba.fastjson.JSONObject> listAttendanceTime(Integer schoolCode, String dynArrangeTableName) {
		return mapper.listAttendanceTime(schoolCode, dynArrangeTableName);
	}

	// C.2.封装cycle_value
	public String getCycleValue() {
		JSONObject cycleValue = new JSONObject();
		String[] weeks = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };
		for (String weekday : weeks) {
			cycleValue.put(weekday, "00:00-24:00");
		}
		return cycleValue.toString();
	}




}

